const uploadToQiNiu = require('../tools/qiniu')
const nanoid = require('nanoid')
const fs = require('fs')
const { apiPreFix, fileSavePath } = require('../config').server
const { formatBody } = require('../tools')
module.exports = (router) => {
  /**
   * 文件上传（存到本地）
   */
  router.post(`${apiPreFix}/com/upload/loc`,async  ctx => {
    if (!ctx.request.body.files.file) {
      ctx.body = formatBody(0, '未收到文件')
    } else {
      const file = [].concat(ctx.request.body.files.file)[0]	// 获取上传文件
      const reader = fs.createReadStream(file.path)	// 创建可读流
      const ext = file.name.split('.').pop()		// 获取上传文件扩展名
      const saveName = `${nanoid()}.${ext}`
      const saveLocPath = `${fileSavePath}/${saveName}`
      const upStream = fs.createWriteStream(saveLocPath)		// 创建可写流
      reader.pipe(upStream)	// 可读流通过管道写入可写流
      ctx.body = formatBody(1, '上传成功', {
        path: `/upload/${saveName}`
      })
    }
  })
  /**
   * 文件上传（前端压缩后以base64上传）
   */
  router.post(`${apiPreFix}/com/upload/base64Img`, async  ctx => {
    let { imgData } = ctx.request.body.fields
    if (!imgData) {
      ctx.body = formatBody(0, '未收到文件')
    } else {
      let base64Data = imgData.replace(/^data:image\/\w+;base64,/, '')
      let dataBuffer = new Buffer(base64Data, 'base64')
      let fileName = `${nanoid()}.jpg`
      // console.log('dataBuffer是否是Buffer对象：' + Buffer.isBuffer(dataBuffer))
      fs.writeFile(`${fileSavePath}/${fileName}`, dataBuffer)
      ctx.body = formatBody(1, 'ok', {
        path: `/upload/${fileName}`
      })
    }
  })
  /**
   * 文件上传（存到七牛）
   */
  router.post(`${apiPreFix}/com/upload/qiniu`,async  ctx => {
    if (!ctx.request.body.files.file) {
      ctx.body = formatBody(0, '未收到文件')
    } else {
      const file = [].concat(ctx.request.body.files.file)[0]
      try{
        let ret = await uploadToQiNiu(`${nanoid()}`, file.path)
        // console.log('文件上传成功', ret)
        ctx.body = formatBody(1, '上传成功', ret)
      } catch (err) {
        console.log('上传失败', err)
        ctx.body = formatBody(1, '上传失败')
      }
    }
  })

}